<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>设备详情</span>
        <el-button type="primary" size="small" @click="goBack" style="float: right;">返回</el-button>
      </div>
      
      <!-- 显示加载状态 -->
      <div v-if="loading" style="text-align: center; padding: 50px;">
        <el-button type="primary" :loading="loading" disabled>
          加载中...
        </el-button>
      </div>

      <!-- 使用DictData组件加载字典数据 -->
      <dict-data />
      
      <!-- 标签页 -->
      <el-tabs v-model="activeTab" type="card">
        <!-- 第一页 - 显示用户指定的主要字段 -->
        <el-tab-pane label="基本信息" name="first">
          <div class="detail-container">
            <el-form>
            <!-- 第一行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="IT设备编码">
                  <el-input v-model="detailData.deviceCode" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备类型">
                  <el-input :value="detailData.typeName" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="型号">
                  <el-input v-model="detailData.model" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="品牌">
                  <el-input :value="detailData.brandName || getDictLabel('device_brand', detailData.brandId)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="密级">
                  <el-input :value="detailData.securityName || getDictLabel('secret_level', detailData.securityId)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="来源">
                  <el-input :value="detailData.sourceName || getDictLabel('device_source', detailData.sourceId)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="所属部门">
                  <el-input :value="detailData.deptName || '未知部门'" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="责任人编号">
                  <el-input v-model="detailData.userId" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="责任人姓名">
                  <el-input v-model="detailData.userName" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第四行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="12">
                <el-form-item label="设备用途">
                  <el-input :value="getDictLabel('device_purpose', detailData.purposeId) || detailData.purposeName" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第五行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="水印编码">
                  <el-input v-model="detailData.watermarkCode" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="水印安装">
                  <el-input :value="getDictLabel('sys_yes_no', detailData.watermarkInstall)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="电子钥匙安装">
                  <el-input :value="getDictLabel('sys_yes_no', detailData.electronicKeyInstall)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第六行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="多网卡使用">
                  <el-input :value="getDictLabel('ban_or_admit', detailData.mulitNetworkCardsUse)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="无线网卡使用">
                  <el-input :value="getDictLabel('none_or_adit_or_ban', detailData.wlanCardUse)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="串口使用">
                  <el-input :value="getDictLabel('none_or_adit_or_ban', detailData.serialPortUse)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第七行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="并口使用">
                  <el-input :value="getDictLabel('none_or_adit_or_ban', detailData.parallelPortUse)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="红外蓝牙使用">
                  <el-input :value="getDictLabel('none_or_adit_or_ban', detailData.infraredBluetoothUse)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="网络共享访问">
                  <el-input :value="getDictLabel('ban_or_admit', detailData.networkSharedAccessUse)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第八行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="记录本地文件操作">
                  <el-input :value="getDictLabel('use_or_not', detailData.fileRecordOperate)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="网络打印">
                  <el-input :value="getDictLabel('use_or_not', detailData.printerUse)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="本地打印">
                  <el-input :value="getDictLabel('ban_or_admit', detailData.localPrintInstall)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第九行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="移动存储设备">
                  <el-input :value="getDictLabel('admit_or_ban_or_reg', detailData.removableStorage)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="移动存储设备读写模式">
                  <el-input :value="getDictLabel('r_w', detailData.removableStorageRwMode)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="相机录音笔">
                  <el-input :value="getDictLabel('admit_or_ban_or_reg', detailData.cameraRecorder)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第十行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="光驱">
                  <el-input :value="getDictLabel('admit_or_ban_or_readonly', detailData.cdRom)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="软驱">
                  <el-input :value="getDictLabel('admit_or_ban_or_innersys', detailData.floppyDrive)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="PCMCIA卡使用">
                  <el-input :value="getDictLabel('ban_or_admit', detailData.pcmciaUse)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第十一行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="对拷线使用">
                  <el-input :value="getDictLabel('ban_or_admit', detailData.duplicateLineUse)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="是否有其他">
                  <el-input :value="getDictLabel('sys_yes_no', detailData.isAnythingElse)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 其他信息 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="24">
                <el-form-item v-if="detailData.isAnythingElse === '1'" label="其他信息">
                  <el-input v-model="detailData.otherInfo" type="textarea" rows="4" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 第二页 - 显示剩余的字段 -->
        <el-tab-pane label="扩展信息" name="second">
          <div class="detail-container">
            <el-form>
            <!-- 第一行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="地理位置">
                  <el-input v-model="detailData.dictName" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系方式">
                  <el-input v-model="detailData.contact" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="网络类型">
                  <el-input :value="getDictLabel('network_type', detailData.networkId)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第二行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="操作系统类型">
                  <el-input :value="getDictLabel('os_type', detailData.osId)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="操作系统安装日期">
                  <el-input :value="parseTime(detailData.osInstallDate, '{y}-{m}-{d}')" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备序列号">
                  <el-input v-model="detailData.deviceSerial" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="CPU核心数">
                  <el-input v-model="detailData.numberOfCpu" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="内存容量">
                  <el-input v-model="detailData.memoryCapacity" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第四行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="启用日期">
                  <el-input :value="parseTime(detailData.activationDate, '{y}-{m}-{d}')" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="使用情况">
                  <el-input :value="getDictLabel('usage_status', detailData.usageId)" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="电子钥匙编号">
                  <el-input v-model="detailData.keyCode" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第五行 -->
            <el-row :gutter="20" class="mb10">
              <el-col :span="8">
                <el-form-item label="用户部门ID">
                  <el-input v-model="detailData.userDeptId" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用户部门名称">
                  <el-input v-model="detailData.userDeptName" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="资产与用户部门是否一致">
                  <el-input :value="detailData.isUserDeptDiff === '1' ? '是' : '否'" disabled placeholder="暂无数据" />
                </el-form-item>
              </el-col>
            </el-row>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
// 导入必要的API和工具函数
import { getDeviceManage } from "@/api/manage/deviceManage";
import DictData from "@/components/DictData";
import { parseTime, selectDictLabel } from '@/utils/ruoyi'

export default {
  name: 'DeviceDetail',
  components: {
    DictData
  },
  data() {
    return {
      // 详情数据 - 提供默认值，防止页面空白
      detailData: {
        // 基础信息 - 所有在模板中使用的字段都需要在此定义
      deviceCode: '加载中...',
      typeId: '',
      typeName: '加载中...',
      model: '加载中...',
      brandId: '',
      brandName: '加载中...',
      securityId: '',
      securityName: '加载中...',
      sourceId: '',
        deptId: '',
        deptName: '加载中...',
        userId: '',
        userName: '加载中...',
        purposeId: '',
        purposeName: '',
        watermarkCode: '',
        watermarkInstall: '0',
        electronicKeyInstall: '0',
        mulitNetworkCardsUse: '0',
        wlanCardUse: '0',
        serialPortUse: '0',
        parallelPortUse: '0',
        infraredBluetoothUse: '0',
        networkSharedAccessUse: '0',
        fileRecordOperate: '0',
        printerUse: '0',
        localPrintInstall: '0',
        removableStorage: '0',
        removableStorageRwMode: '0',
        cameraRecorder: '0',
        cdRom: '0',
        floppyDrive: '0',
        pcmciaUse: '0',
        duplicateLineUse: '0',
        isAnythingElse: '0',
        otherInfo: '无',
        
        // 扩展信息
        geographicLocation: '加载中...', // 修复地理位置字段
        contact: '',
        networkId: '',
        osId: '',
        osInstallDate: '',
        deviceSerial: '',
        numberOfCpu: '',
        memoryCapacity: '',
        activationDate: '',
        usageId: '',
        keyCode: '',
        userDeptId: '',
        userDeptName: '',
        isUserDeptDiff: '0',
        
        // 字典名称字段（为了兼容现有代码）
        dictName: '加载中...'
      },
      // 活跃标签页
      activeTab: 'first',
      // 加载状态
      loading: true,
      // 设备ID
      deviceId: '',
      // 数据加载完成标志
      dataLoaded: false,
      // 错误信息
      errorMessage: ''
    }
  },
  // 生命周期钩子
    created() {
      // 直接在created中获取设备ID
      this.deviceId = this.$route.params.deviceId || ''
      console.log('设备详情页面初始化，设备ID:', this.deviceId)
      
      // 获取路由查询参数中的中文名称
      const queryParams = this.$route.query || {}
      if (queryParams.brandName) {
        this.detailData.brandName = queryParams.brandName
      }
      if (queryParams.securityName) {
        this.detailData.securityName = queryParams.securityName
      }
      if (queryParams.sourceName) {
        this.detailData.sourceName = queryParams.sourceName
      }
      
      // 立即加载数据
      this.fetchDeviceData()
    },
  
  // 方法定义
  methods: {
    // 获取设备数据
    fetchDeviceData() {
      // 检查设备ID是否存在
      if (!this.deviceId) {
        this.handleError('设备ID不存在')
        return
      }

      console.log('开始获取设备ID:', this.deviceId, '的数据')
      
      // 使用setTimeout模拟网络延迟，确保用户看到加载状态
      setTimeout(() => {
        this.loading = true
        
        // 调用API获取数据
      getDeviceManage(this.deviceId)
        .then(data => {
          console.log('API返回数据:', data)
          
          // 处理API返回的数据 - request.js已经直接返回了res.data
          this.handleSuccess(data)
        })
        .catch(error => {
          console.error('获取设备数据失败:', error)
          this.handleError('获取设备数据失败: ' + (error.message || '未知错误'))
        })
      }, 300) // 短暂延迟，让用户看到加载效果
    },
    
    // 处理成功响应
    handleSuccess(data) {
      console.log('处理成功数据:', data)
      console.log('数据类型:', typeof data)
      
      try {
        // 处理不同可能的数据格式
        if (typeof data === 'object' && data !== null) {
          console.log('API返回的是对象数据，准备处理')
          
          // 如果数据中有data字段（有些API会嵌套数据）
          if (data.data) {
            console.log('发现嵌套的data字段，提取中...')
            data = data.data
            console.log('嵌套的data字段内容:', data)
          }
          
          // 使用Vue的$set方法确保响应式更新
          Object.keys(data).forEach(key => {
            if (data[key] !== null && data[key] !== undefined) {
              console.log(`更新字段 ${key}:`, data[key])
              // 如果detailData中已经定义了这个key，直接赋值
              if (key in this.detailData) {
                this.detailData[key] = data[key]
              } else {
                // 如果是新字段，使用$set确保响应式
                this.$set(this.detailData, key, data[key])
              }
            }
          })
          
          // 确保地理位置字段有值
          if (!this.detailData.geographicLocation && this.detailData.dictName) {
            this.detailData.geographicLocation = this.detailData.dictName
          }
          
          console.log('数据合并完成后:', this.detailData)
        } else {
          console.log('API返回的数据不是对象，类型为:', typeof data)
          // 如果数据不是对象，尝试解析它（可能是字符串形式的JSON）
          try {
            console.log('尝试解析非对象数据...')
            const parsedData = JSON.parse(data)
            console.log('解析成功，数据为:', parsedData)
            
            // 合并解析后的数据
            Object.keys(parsedData).forEach(key => {
              if (parsedData[key] !== null && parsedData[key] !== undefined) {
                if (key in this.detailData) {
                  this.detailData[key] = parsedData[key]
                } else {
                  this.$set(this.detailData, key, parsedData[key])
                }
              }
            })
          } catch (parseError) {
            console.warn('数据解析失败，使用默认数据:', parseError)
            console.log('API返回的原始数据:', data)
          }
        }
      } catch (error) {
        console.error('处理数据时出错:', error)
        // 出错时也显示一些默认数据
        this.handleError('数据处理错误')
        return
      }
      
      // 更新状态
      this.loading = false
      this.dataLoaded = true
      
      console.log('最终显示的数据:', this.detailData)
      // 显示成功消息
      if (this.$message) {
        this.$message.success('数据加载成功')
      }
    },
    
    // 处理错误情况
    handleError(message) {
      console.warn('处理错误:', message)
      
      // 设置错误信息
      this.errorMessage = message
      
      // 即使出错，也显示一些模拟数据
      // 注意：这里不覆盖整个detailData对象，只更新必要的字段
      this.detailData.deviceCode = '示例设备-' + this.deviceId
      this.detailData.typeName = '未知设备类型'
      this.detailData.model = '未知型号'
      this.detailData.brandName = '未知品牌'
      this.detailData.deptName = '未知部门'
      this.detailData.userName = '未知用户'
      
      // 更新状态
      this.loading = false
      this.dataLoaded = true
      
      // 显示错误提示
      if (this.$message) {
        this.$message.error(message)
      } else {
        console.error(message)
      }
    },
    
    // 正确的字典标签获取函数
    getDictLabel(dictType, value) {
      // 如果没有值，直接返回'无'
      if (!value && value !== 0) return '无'
      
      try {
        // 使用导入的selectDictLabel函数
        // 先尝试直接使用字典类型名称和值
        try {
          const label = selectDictLabel(dictType, value)
          return label || value
        } catch (e) {
          console.log('直接使用字典类型名称失败，尝试获取字典数据:', e)
          
          // 尝试从store中获取字典数据
          const dictData = this.$store.getters && this.$store.getters.dictData ? this.$store.getters.dictData : {}
          const dictArray = dictData[dictType] || []
          
          if (dictArray && dictArray.length > 0) {
            // 如果有字典数据，使用selectDictLabel
            const label = selectDictLabel(dictArray, value)
            return label || value
          } else {
            // 如果没有字典数据，直接返回值
            console.warn(`字典类型 ${dictType} 没有数据`)
            return value
          }
        }
      } catch (error) {
        console.warn('获取字典标签失败:', error)
        return value
      }
    },
    
    // 返回上一页
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.detail-container {
  padding: 10px 0;
}
.mb10 {
  margin-bottom: 10px;
}
.el-form-item {
  margin-bottom: 15px;
}
.el-form-item__label {
  font-weight: 500;
  color: #606266;
}
.el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #303133;
}
</style>
